const Router = require('koa-router')
const user = require('../../models/user')
const router = new Router({
    prefix: "/api/admin/user"
})

const User = require('../../models/user')
const {
    Success,
    Error
} = require('../../utils/response')

router.get('/search', async (ctx) => {

    let {
        username
    } = ctx.request.query
    let userList = await User.findAll({
        where: {
            username
        }
    })
    ctx.body = Success(userList);

})

router.get('/userinfo', async (ctx) => {

    let {
        id
    } = ctx.request.query
    let userList = await User.findAll({
        where: {
            id
        }
    })
    ctx.body = Success(userList);

})

router.get('/user', async (ctx) => {

    let {
        page = 1
    } = ctx.request.query
    let offset = (page - 1) * 10;
    let userList = await User.findAndCountAll({
        offset,
        limit: 10,
        order: [
            ['id', 'DESC']
        ]
    })
    ctx.body = Success(userList);

})

router.post('/user', async (ctx) => {

    let {
        username,
        password,
        address
    } = ctx.request.body
    if (!username || !address || !password) {
        ctx.body = Error('未携带指定参数')
    } else {
        let user = await User.findOne({
            where: {
                username
            }
        })
        if (!user) {
            let user = await User.create({
                username,
                password,
                address
            })
            ctx.body = Success(user, '添加成功');
        } else {
            ctx.body = Error('该用户已经存在');
        }

    }


})

router.put('/user', async (ctx) => {

    let {
        id,
        username,
        password,
        address
    } = ctx.request.body
    if (!id || !username || !address || !password) {
        ctx.body = Error('未携带指定参数')
    } else {
        let user = await User.update({
            username,
            password,
            address
        }, {
            where: {
                id
            }
        })
        if (user[0] == 1) {
            ctx.body = Success('', '修改成功');
        } else {
            ctx.body = Success('', '修改失败');
        }

    }


})

router.delete('/user', async (ctx) => {

    let {
        id,
    } = ctx.request.body
    if (!id) {
        ctx.body = Error('未携带指定参数')
    } else {
        let user = await User.destroy({
            where: {
                id
            }
        })
        if (user == 1) {
            ctx.body = Success('', '删除成功');
        } else {
            ctx.body = Success('', '删除失败');
        }

    }


})

module.exports = router